using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
namespace Bamboo.Core.Common.Email
{
    public class EmailSender
    {
        private int port;
        private string host;
        private string userName;
        private string password;
        private bool needAuthentication = true;
        private SmtpClient smtpClient;
        public bool NeedAuthentication
        {
            get { return needAuthentication; }
            set { needAuthentication = value; }
        }
	
        public string Password
        {
            get { return password; }
            set { password = value; }
        }
	
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
	
        public string Host
        {
            get { return host; }
            set { host = value; }
        }
	
        public int Port
        {
            get { return port; }
            set { port = value; }
        }

        private void Initialize()
        {
            smtpClient = new SmtpClient(host, port);
            if (NeedAuthentication)
            {
                smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
            }
        }

        public void Send(string from, string to, string subject, string body)
        {
            if (smtpClient == null)
            {
                Initialize();
            }
            try
            {
                Email email = new Email(subject, from, to, body);    
                MailMessage mailMessage = CreateMailMessage(email);
                smtpClient.Send(mailMessage);
            }
            catch (Exception ex)
            {
                
            }
        }

        protected MailMessage CreateMailMessage(Email template)
        {
            MailMessage mailMessage = new MailMessage(template.From, template.To,
                    template.Subject, template.Body);
            mailMessage.IsBodyHtml = !String.IsNullOrEmpty(template.BodyContentType) && template.BodyContentType.Equals("text/html");
            if (template.LinkedResources != null && template.LinkedResources.Count > 0)
            {
                AlternateView view = AlternateView.CreateAlternateViewFromString(template.Body, template.BodyEncoding, System.Net.Mime.MediaTypeNames.Text.Html);
                foreach (LinkedResource linkedResource in template.LinkedResources)
                {
                    view.LinkedResources.Add(linkedResource);
                }
                mailMessage.AlternateViews.Add(view);
            }
            return mailMessage;
        }
    }
}
